package com.example.myapplication.function.musicmode

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Log
import androidx.core.app.ActivityCompat

/**
 * 1. 音频录制模块
 */
class AudioRecorder(
    private val onAudioData: (FloatArray) -> Unit
) {
    private var recorder: AudioRecord? = null
    private var isRecording = false
    private var recordingThread: Thread? = null

    companion object {
        private const val SAMPLE_RATE = 44100
        private const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
        private const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
        private const val BUFFER_SIZE = 1024

        // 计算最小缓冲区大小
        fun getMinBufferSize(): Int {
            return AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT)
        }
    }

    fun startRecording() {
        if (isRecording) {
            Log.w("AudioRecorder", "Already recording")
            return
        }

        try {
            val minBufferSize = getMinBufferSize()
            if (minBufferSize == AudioRecord.ERROR_BAD_VALUE) {
                Log.e("AudioRecorder", "Invalid buffer size")
                return
            }

            // 创建AudioRecord实例
            recorder = AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                minBufferSize * 2 // 使用两倍最小缓冲区
            )

            when (recorder?.state) {
                AudioRecord.STATE_UNINITIALIZED -> {
                    Log.e("AudioRecorder", "AudioRecord not initialized")
                    return
                }
                AudioRecord.STATE_INITIALIZED -> {
                    Log.d("AudioRecorder", "AudioRecord initialized successfully")
                }
            }

            recorder?.startRecording()
            isRecording = true

            // 启动录音线程
            recordingThread = Thread(RecordingRunnable())
            recordingThread?.start()

            Log.d("AudioRecorder", "Recording started")

        } catch (e: SecurityException) {
            Log.e("AudioRecorder", "Audio record permission denied", e)
        } catch (e: Exception) {
            Log.e("AudioRecorder", "Error starting recording", e)
        }
    }

    fun stopRecording() {
        if (!isRecording) {
            return
        }

        isRecording = false

        try {
            recorder?.let { audioRecord ->
                if (audioRecord.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
                    audioRecord.stop()
                }
                audioRecord.release()
            }
            recorder = null

            recordingThread?.join(1000) // 等待录音线程结束
            recordingThread = null

            Log.d("AudioRecorder", "Recording stopped")
        } catch (e: Exception) {
            Log.e("AudioRecorder", "Error stopping recording", e)
        }
    }

    fun isRecording(): Boolean {
        return isRecording
    }

    fun getSampleRate(): Int {
        return SAMPLE_RATE
    }

    private inner class RecordingRunnable : Runnable {
        override fun run() {
            val buffer = ShortArray(BUFFER_SIZE)
            val floatBuffer = FloatArray(BUFFER_SIZE)

            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO)

            while (isRecording) {
                try {
                    val readResult = recorder?.read(buffer, 0, BUFFER_SIZE) ?: 0

                    when {
                        readResult == AudioRecord.ERROR_INVALID_OPERATION -> {
                            Log.e("AudioRecorder", "ERROR_INVALID_OPERATION")
                            break
                        }
                        readResult == AudioRecord.ERROR_BAD_VALUE -> {
                            Log.e("AudioRecorder", "ERROR_BAD_VALUE")
                            break
                        }
                        readResult == AudioRecord.ERROR_DEAD_OBJECT -> {
                            Log.e("AudioRecorder", "ERROR_DEAD_OBJECT")
                            break
                        }
                        readResult > 0 -> {
                            // 将16位PCM转换为float (-1.0 到 1.0)
                            for (i in 0 until readResult) {
                                floatBuffer[i] = buffer[i] / 32768.0f
                                // 限制在-1.0到1.0之间
                                if (floatBuffer[i] > 1.0f) floatBuffer[i] = 1.0f
                                if (floatBuffer[i] < -1.0f) floatBuffer[i] = -1.0f
                            }

                            // 回调音频数据
                            onAudioData(floatBuffer.copyOf(readResult))
                        }
                        readResult == 0 -> {
                            // 没有数据可读，短暂休眠
                            Thread.sleep(10)
                        }
                    }
                } catch (e: Exception) {
                    Log.e("AudioRecorder", "Error in recording thread", e)
                    break
                }
            }

            Log.d("AudioRecorder", "Recording thread finished")
        }
    }

}